<?php namespace App\Api\Http\ApiControllers;

use App\Exceptions\OtherException;
use App\Api\Http\Requests\ItemRequest;
use App\Models\ItemStage;
use App\Models\Tag;
use App\Repositories\Eloquent\Item\Entity\ItemEntity;
use App\Repositories\Item\CompanyRepositoryInterface;
use App\Repositories\Item\ItemRepositoryInterface;
use App\Repositories\Item\ProjectRepositoryInterface;
use App\Repositories\Tag\TagRepositoryInterface;
use Illuminate\Http\Request;

class PublisherItemController extends Controller
{
    /**
     * @var ProjectRepositoryInterface
     */
    protected $project_repository;

    /**
     * @var CompanyRepositoryInterface
     */
    protected $company_repository;

    /**
     * @var ItemRepositoryInterface
     */
    protected $item_repository;

    public function __construct(
        ProjectRepositoryInterface $project_repository,
        CompanyRepositoryInterface $company_repository,
        ItemRepositoryInterface $item_repository
    ) {
        $this->project_repository = $project_repository;
        $this->company_repository = $company_repository;
        $this->item_repository = $item_repository;
    }

    public function index(Request $request)
    {
        $per_page = $request->get('per_page', 10);
        $lists = $this->item_repository->getPublisherItems(access()->id(), $per_page);
        $lists->load('contact', 'company', 'project.contact', 'publisher', 'stage', 'tags');

        return response()->json($lists->toArray());
    }

    public function show($id)
    {
        $item = $this->item_repository->show((int)$id);
        throw_unless($item, new OtherException('信息不存在'));

        throw_if($item->publisher_uid != access()->id(), new OtherException('没有权限查看'));

        $item->load('contact', 'company', 'project.contact', 'stage', 'publisher', 'tags');

        return response()->json($item->toArray());
    }

    public function store(ItemRequest $request)
    {
        $entity = $this->createItemEntity($request);

        $this->item_repository->store($entity);

        return response('', 201);
    }

    public function update($id, ItemRequest $request)
    {
        $entity = $this->createItemEntity($request);

        $this->item_repository->update($id, $entity);

        return response('', 204);
    }

    public function finish($id)
    {
        $this->item_repository->publisherFinish($id, access()->id());

        return response('', 204);
    }

    private function createItemEntity(Request $request)
    {
        $user_id = access()->id();
        $item = new ItemEntity();
        $item->publisher_uid = $user_id;
        $item->company_id = $request->get('company_id');
        if (!$this->company_repository->checkUserHasCompany($user_id, $item->company_id)) {
            throw new OtherException('公司选择错误');
        }
        $item->project_id = $request->get('project_id');
        if (!$this->project_repository->checkUserHasProject($user_id, $item->project_id)) {
            throw new OtherException('项目选择错误');
        }
        $item->department = $request->get('department');
        $item->contact_name = $request->get('contact_name');
        $item->contact_phone = $request->get('contact_phone');
        $item->title = $request->get('title');
        $item->stage = $request->get('stage');
        $item->price = $request->get('price');
        $item->description = $request->get('description');
        $item->expired_at = $request->get('expired_at');
        $item->tag_ids = $request->get('tag_ids');

        return $item;
    }

    public function config()
    {
        $user_id = access()->id();
        $lists = $this->item_repository->getPublisherItems($user_id, 20);
        $lists->load('company', 'project.contact');

        $companies = $projects = [];
        foreach ($lists as $list) {
            $company = $list->company;
            $project = $list->project;
            $companies[$company->id] = $company->toArray();
            $projects[$project->id] = $project->toArray();
        }

        $user_companies = $this->company_repository->lists($user_id, 20);
        $user_projects = $this->project_repository->lists($user_id, 20);
        $user_projects->load('contact');

        foreach ($user_companies as $user_company) {
            $companies[$user_company->id] = $user_company->toArray();
        }

        foreach ($user_projects as $user_project) {
            $companies[$user_project->id] = $user_project->toArray();
        }

        $stage = ItemStage::query()->latest('sort')->get(['id', 'name']);

        /** @var TagRepositoryInterface $tag_repository */
        $tag_repository = app(TagRepositoryInterface::class);
        $tags = $tag_repository->getByType(Tag::TYPE_OF_ITEM);

        $result = [
            'companies' => array_values($companies),
            'projects'  => array_values($projects),
            'stages'    => $stage,
            'tags'      => $tags->map(function ($item) {
                return $item->only('id', 'name');
            }),
        ];

        return response()->json($result);
    }
}
